<?php
/**
 * Short Description  
 *
 * Long Description 
 *
 * @category   
 * @package    
 * @subpackage 
 * @copyright 
 * @author     Sandeep Manne<sandeep.manne@costrategix.com>
 */

//require_once "Abstract.php";

class Core_Social_Adapter_Linkedin //extends Core_Social_Adapter_Abstract
{
	private $_callbackUrl          = "";
	private $_siteUrl              = "https://api.linkedin.com/uas/oauth/";
	private $_requestTokenUrl      = "https://api.linkedin.com/uas/oauth/requestToken";
	private $_userAuthorizationUrl = "https://api.linkedin.com/uas/oauth/authorize";
	private $_accessTokenUrl	   = "https://api.linkedin.com/uas/oauth/accessToken";
	private $_consumerKey          = "";
	private $_consumerSecret	   = "";
	private $_consumer             = null;
	private $_config               = array();
	
	public function setConsumerKey($key)
	{
		$this->_consumerKey = $key;	
	}
	
	public function setConsumerSecret($key)
	{
		$this->_consumerSecret = $key;	
	}
	
	public function setCallBackUrl($url)
	{
		$this->_callbackUrl = $url;
	}
	
	public function __construct($config)
	{
		$this->_config = $config;
		$this->_consumer = new Zend_Oauth_Consumer($this->_config);
	}
	
	public function getRequestToken()
	{
		$requestToken = $this->_consumer->getRequestToken();
		$linkedinSession = new Zend_Session_Namespace('linkedin');
        $linkedinSession->requestToken = serialize($requestToken);
        $this->_consumer->redirect();
	}
	
	public function getAccessToken($response)
	{
		$linkedinSession = new Zend_Session_Namespace('linkedin');
		$accessToken = $this->_consumer
					  		->getAccessToken(
					  				   		 $response, 
					  				   		 unserialize($linkedinSession->requestToken)
					  				  		);
		$linkedinSession->accessToken = serialize($accessToken);
		Zend_Auth::getInstance()->getStorage()->write(array("adapter" => "linkedin"));
	}
	
	public function getFriends($profileId = null)
	{
		if (!$profileId) $profileId = "~";
		$content = $this->_get("https://api.linkedin.com/v1/people/{$profileId}/connections");
		return simplexml_load_string($content);
	}
	
	public function hasAccess()
	{
		$linkedinSession = new Zend_Session_Namespace('linkedin');
		return unserialize($linkedinSession->accessToken);
	}
	
	private function _getClient()
	{
		$linkedinSession = new Zend_Session_Namespace('linkedin');
		$accessToken 	 = unserialize($linkedinSession->accessToken);
		return $accessToken->getHttpClient($this->_config);
	}
	
	private function _get($uri)
	{
		return $this->_getClient()
				     ->setUri($uri)
				     ->setMethod(Zend_Http_Client::GET)
				     ->request()
				     ->getBody();
	}
	
	public function getDetails($profileId = null)
	{
		if (!$profileId) $profileId = "~";
		$content = $this->_get("https://api.linkedin.com/v1/people/{$profileId}:public");
		return simplexml_load_string($content);
	}
}